<?php

class Article extends Block
{
	const TABLE = 'article';
	
	public static function assertInstallation() {
		Data::table_exists(self::TABLE) or
			Data::query('CREATE TABLE IF NOT EXISTS '.self::TABLE.' (id INTEGER, content)');
	}
	
	public static function get($id) {
		$article = @Data::first('SELECT * FROM '.self::TABLE.' WHERE id = '.$id);

		if (!isset($article['content'])) {
			self::assertInstallation();
			// Return an empty article
			// TODO: Is this the best idea here?
			return new self;
		}
		
		$article = self::makeObj($article);
		
		return $article;
	}
	
	public static function create($name = '/') {
		self::assertInstallation();
		$article = array();
		
		$article['id'] = Area::register(self::makeObj($article), $name);
		$article['content'] = '<h1>New Article</h1><p>Double-click to edit.</p>';
		
		Data::insert(self::TABLE, $article);
		
		return $article;
	}
	
	public static function delete($id) {
		Area::unregister($id);
		Data::query('DELETE FROM '.self::TABLE.' WHERE id = '.$id);
	}
	
	public static function save($data)
	{
		Data::update(self::TABLE, $data);
	}
	
	public static function makeObj($array)
	{
		$obj = new self;
		$obj->id = $array['id'];
		$obj->content = $array['content'];
		return $obj;
	}
	
	public $content;
	
	public function show()
	{
		Design::load('modules/article/article.tpl.php', array('article' => $this));
	}
}
?>